# -*- coding:utf-8 -*-
__author__ = 'xigu007'
import kivy
from kivy.clock import Clock
from kivy.graphics import Color, Rectangle,Ellipse
from kivy.metrics import dp,sp
from kivy.properties import NumericProperty, OptionProperty
from kivy.uix.carousel import Carousel
from kivy.uix.widget import Widget
from distutils.version import LooseVersion
_kivy_1_9_1 = LooseVersion(kivy.__version__) >= LooseVersion('1.9.1')

class IndexBarCarousel(Widget):
    bar_height = NumericProperty(dp(20))
    bar_anchor = OptionProperty('in', options=('out','in'))
    def __init__(self, **kwargs):
        self.crl_size = (dp(8), dp(8))
        self.crl_distance = 5
        self.crl_y = 0
        self.start_x = 0
        self.carousel = None
        self.size_changed = True
        self.slider_nums = 0
        self._trigger_draw_circle = Clock.create_trigger(self._update_circle, -1)
        super(IndexBarCarousel, self).__init__(**kwargs)
        if not kwargs.has_key('loop'):
            kwargs['loop'] = True
        if not kwargs.has_key('min_move'):
            kwargs['min_move'] = 0.05
        carousel = self.carousel = Carousel(**kwargs)
        fbind = carousel.fbind if _kivy_1_9_1 else carousel.fast_bind
        fbind('index', self.carousel_on_index)
        carousel.parent = self
        self.children.append(carousel)
        self.canvas.add(carousel.canvas)

    def add_widget(self, widget, index=0):
        carousel = self.carousel
        if carousel:
            carousel.add_widget(widget, index)
            self._trigger_draw_circle()

    def remove_widget(self, widget):
        carousel = self.carousel
        if carousel:
            carousel.remove_widget(widget)
            self._trigger_draw_circle()

    def clear_widgets(self):
        carousel = self.carousel
        if carousel:
            carousel.clear_widgets()
            self._trigger_draw_circle()

    def on_pos(self, instance, size):
        self.size_changed = True
        self._trigger_draw_circle()

    def on_size(self, instance, size):
        self.size_changed = True
        self._trigger_draw_circle()

    def on_bar_height(self, instance, value):
        self.size_changed = True
        self._trigger_draw_circle()

    def on_bar_anchor(self, instance, value):
        self.size_changed = True
        #print 'on_bar_anchor'
        self._trigger_draw_circle()

    def carousel_on_index(self, instance, value):
        self._trigger_draw_circle()

    def _update_size_pos(self):
        bar_height = self.bar_height
        if self.bar_anchor == 'out':
            self.carousel.pos = (self.x, self.y + bar_height)
            self.carousel.size = (self.width, self.height - bar_height)
        else:
            self.carousel.pos = self.pos
            self.carousel.size = self.size
        crl_h = 0.5*bar_height
        crl_w = crl_h
        self.crl_size = (crl_w, crl_h)
        self.crl_distance = 0.5*crl_w
        self.crl_y = self.y + 0.2*bar_height
        self.slider_nums = 0
        #print 'self.carousel = {},{}'.format(self.carousel.pos,  self.carousel.size)

    def _update_circle(self, *args):
        if self.size_changed:
            self._update_size_pos()
            self.size_changed = False
        carousel = self.carousel
        canvas = self.canvas.after
        canvas.clear()
        counter = len(carousel.slides)
        if 0 == counter:
            return
        active_index = carousel.index
        if self.slider_nums != counter:
            self.slider_nums = counter
            wd = counter * self.crl_size[0] + (counter - 1)*self.crl_distance
            self.start_x = (self.width - wd) / 2
        start_x = self.start_x
        #print '--counter={}'.format(counter)
        with canvas:
            for i in range(counter):
                Color(.65, .65, .65, .7)
                if i == active_index:
                    Color(.4,.671,.925, 1.0)
                Ellipse(size = self.crl_size, pos = ((start_x + i*(self.crl_size[0] + self.crl_distance)), self.crl_y))

if __name__ == '__main__':
    from kivy.app import  App
    from kivy.lang import Builder
    from kivy.core.text import LabelBase
    from kivy.uix.boxlayout import BoxLayout
    from kivy.uix.button import Button
    from kivy.properties import ListProperty
    from kivy.resources import resource_add_path
    import os
    LabelBase.get_system_fonts_dir()
    resource_add_path('../fonts')
    os.environ['KIVY_VALID_FONT'] = 'SourceHanSansCN-Regular.otf'
    Builder.load_string('''
<BoxLayoutColor>
    canvas.before:
        Color:
            rgb: self.background_color
        Rectangle:
            pos: self.pos
            size: self.size
''')

    class BoxLayoutColor(BoxLayout):
        background_color = ListProperty([.92,.92,.92,1])

    class MyApp(App):
        def build(self):
            root = BoxLayoutColor()
            container = BoxLayout(orientation='vertical')
            root.add_widget(container)
            index_carousel = self.index_carousel = IndexBarCarousel(bar_anchor='in')
            index_carousel.add_widget(Button(text='button1'))
            index_carousel.add_widget(Button(text='button2'))
            #index_carousel.add_widget(Button(text='button3'))
            #index_carousel.add_widget(Button(text='button4'))
            container.add_widget(index_carousel)
            layout = BoxLayout(size_hint=(1, None), height=50)
            layout.add_widget(Button(text='test1', on_release=self._btn_create_composite1))
            layout.add_widget(Button(text='test2', on_release=self._btn_create_composite2))
            layout.add_widget(Button(text='test3', on_release=self._btn_create_composite3))
            #layout.add_widget(Button(text='clear', on_release=self._btn_clear))
            container.add_widget(layout)
            return root

        def _btn_create_composite1(self,*args):
            #print self.label.ids
            if self.index_carousel:
                self.index_carousel.add_widget(Button(text='button1'))

        def _btn_create_composite2(self,*args):
            #print self.label.ids
            if self.index_carousel:
                self.index_carousel.clear_widgets()

        def _btn_create_composite3(self,*args):
            #print self.label.ids
            if self.index_carousel:
                if self.index_carousel.bar_anchor == 'out':
                    self.index_carousel.bar_anchor = 'in'
                else:
                    self.index_carousel.bar_anchor = 'out'

    MyApp().run()